from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.utils.commons import login_user_data
from info.utils.response_code import RET
from . import index_blu


# 用户登陆状态
@index_blu.route('/', methods=['POST', 'GET'])
@login_user_data
def index():
    # current_app.logger.debug('debug')
    # current_app.logger.error('error')
    # user_id = session.get('user_id')
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #         # 用户照片信息七牛云
    #         user.avatar_url = constants.QINIU_DOMIN_PREFIX + user.avatar_url
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user

    # 从数据库中点击获取新闻点击排行
    rank_news_li = []
    try:
        rank_news_li = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)

    # 从数据库中获取所有新闻信息
    categorys = []
    try:
        categorys = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    return render_template('news/index.html', user=user, rank_news_li=rank_news_li, categorys=categorys)


# 网页图标
@index_blu.route('/favicon.ico')
def send_web_ico():
    return current_app.send_static_file('news/favicon.ico')


@index_blu.route('/news', methods=['GET'])
def get_news_list():
    """
    获取分类新闻信息:
    1. 接收参数(新闻分类id，页码，每页容量)并进行参数校验
    2. 根据category_id查询分类新闻信息并分页
    3. 遍历分类信息对象列表，将每个对象转化为字典数据
    4. 返回应答
    """
    # 接收参数
    category_id = request.args.get('cid')
    page = request.args.get('page', 1)
    per_page = request.args.get('per_page', constants.HOME_PAGE_MAX_NEWS)
    # 判断是否为空
    if not category_id:
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    # 取得的三个值后续操作时，必须是int类型
    try:
        category_id = int(category_id)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 2. 根据category_id查询分类新闻信息并分页
    filters = []

    # 第一页为最新消息，用新闻表中的创建日期排列，且该表中所有分类信息均在此表中

    # 则先判断，不为第一页则分类则按分类取
    if category_id != 1:
        filters.append(News.category_id == category_id)

    # 第一项的时候直接按照创建时间排序
    try:
        # pagination = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page, per_page, False)
        pagination = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        # 获取当前页的所有数据,news_li是一个列表，其中的每一个元素都是News的一个实例对象
        news_li = pagination.items
        # 总页数
        total_page = pagination.pages
        # 当前页数
        current_page = pagination.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取分类新闻信息失败')
    # 3. 遍历分类信息对象列表，将每个对象转化为字典数据
    news_dict_li = []
    for news in news_li:
        news_dict_li.append(news.to_basic_dict())
        # jsonify 会将 news_li\total_page\current_page 封装成json型数据 传给前端
    return jsonify(errno=RET.OK, errmsg='OK',
                   news_li=news_dict_li,
                   total_page=total_page,
                   current_page=current_page)
